package com.sinai.mshab.client.search;

import java.util.ArrayList;

import com.google.gwt.user.client.ui.ListBox;
import com.sinai.mshab.client.util.Observable;
import com.sinai.mshab.client.util.Observer;

/**
 * A dropdown list allowing the user to select by which fields to sort their
 * results by in {@link AdvancedSearch}
 * 
 * @author serge
 * 
 */
public class SortByWidget extends ListBox implements Observer {

	private static SortByWidget instance;
	private ArrayList alreadyIn = new ArrayList();

	private SortByWidget() {

	}

	/**
	 * Retreives the instance of the sort by widget.
	 * 
	 * @return
	 */
	public static SortByWidget getInstance() {
		if (instance == null) {
			instance = new SortByWidget();
		}
		return instance;
	}

	/**
	 * This method is called by observers, namely {@link SearchField}s to
	 * notify this list of their existance
	 */
	public void update(Observable o, Object arg) {
		if (o instanceof SearchField) {
			SearchField field = (SearchField) o;
			String state = (String) arg;

			String table = field.getTableName();
			String name = field.getField();
			String composite = name + " (" + table + ")";

			// add anything new
			if (state.equals(SearchField.CREATED_STATE)) {

				// do not add the same thin several times
				if (!alreadyIn.contains(composite)) {
					alreadyIn.add(composite);
					addItem(composite);
				}
			}
		}
	}
}
